package com.umeox.watch.moto.pedometer.util;

import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;

import com.umeox.watch.moto.apiclient.model.StepRankingDTO;
import com.umeox.watch.moto.dataservice.proxy.PushApiClientProxy;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedHashSet;

/**
 * Created by Rambo 2019-12-10
 * Describe:
 */
public class StepManager {
    public static final String ACTION_PEDOMETER_RESET = "com.wherecom.intent.action.PEDOMETER_RESET";
    public static final String STEP_COUNTS = "/sys/class/input/input1/step_counts";
    public static final String RESET_NODE = "/sys/class/input/input1/step_counts";
    private volatile static StepManager instance;
    private static final String TAG = "StepManager";
    private LinkedHashSet<StepInfoChangeListener> mStepInfoChangeListeners = new LinkedHashSet<>();

    public LinkedHashSet<StepInfoChangeListener> getListeners() {
        return mStepInfoChangeListeners;
    }


    private String mStepCountsNode;

    private StepManager() {

    }

    public void addStepInfoChangeListener(StepInfoChangeListener stepInfoChangeListener) {
        mStepInfoChangeListeners.add(stepInfoChangeListener);
        if (mOnPedometerRegisteredListener != null) {
            mOnPedometerRegisteredListener.onRegistered();
        }
    }

    public void removeStepInfoChangeListener(StepInfoChangeListener stepInfoChangeListener) {
        mStepInfoChangeListeners.remove(stepInfoChangeListener);
    }

    public static StepManager getInstance() {
        if (instance == null) {
            synchronized (StepManager.class) {
                if (instance == null) {
                    instance = new StepManager();
                }
            }
        }
        return instance;
    }

    private String getStepCountNode() {
        return TextUtils.isEmpty(mStepCountsNode) ? STEP_COUNTS : mStepCountsNode;
    }

    public void setStepCountsNode(String currentStepCountNode){
        this.mStepCountsNode = currentStepCountNode;
    }

    /**
     * 通过节点获取步数,从节点读出数据为1, 说明步数为0
     *
     * @return 返回步数
     */
    public synchronized int getStepCounts() {
        FileInputStream in = null;
        int count = 0;
        BufferedReader bReader = null;
        try {
            File fp = new File(getStepCountNode());
            in = new FileInputStream(fp);
            bReader = new BufferedReader(new InputStreamReader(in));
            String str = bReader.readLine();
            count = Integer.parseInt(str);
            Log.e(TAG, "count=" + count);
        } catch (Exception e) {
            Log.v(TAG, "getStepCounts: ", e);
        } finally {
            close(in);
            close(bReader);
        }

        return count == 1 ? 0 : count;
    }


    /**
     * 解绑和重启的时候，需要手动清空记步芯片数据
     * Mimo 手表和手机项目要清楚固定节点
     */
    public synchronized void resetSensorFlag() {
        FileWriter fw = null;
        try {
            fw = new FileWriter(RESET_NODE);
            fw.write("1");
            fw.flush();
            LogUtils.saveLog("-->resetSensorFlag: 1");
        } catch (Exception e) {
            Log.v(TAG, "resetSensorFlag: ", e);
            LogUtils.saveLog("-->resetSensorFlag: " + e);
        } finally {
            close(fw);
        }
    }

    /**
     * 关流
     *
     * @param in
     */
    private void close(Closeable in) {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public interface StepInfoChangeListener {
        void onStepInfoChange(int steps, int target, double height, double weight);
    }

    private OnPedometerRegisteredListener mOnPedometerRegisteredListener;

    public void setOnPedometerRegisteredListener(OnPedometerRegisteredListener onPedometerRegisteredListener) {
        mOnPedometerRegisteredListener = onPedometerRegisteredListener;
    }

    public interface OnPedometerRegisteredListener {
        void onRegistered();
    }

    public String getCurrentStepNodePath() {
        for (int i = 0; i < 8; i++) {
            String nodePath = "/sys/class/input/input" + i + "/name";
            String name = getNodeName(nodePath);
            Log.e("TAG", "name =" + name);
            if ("accelerometer".equals(name)) {
                return nodePath;
            }
        }
        return null;
    }

    private String getNodeName(String nodePath) {
        FileInputStream in = null;
        BufferedReader bReader = null;
        String str = "";
        try {
            File fp = new File(nodePath);
            in = new FileInputStream(fp);
            bReader = new BufferedReader(new InputStreamReader(in));
            str = bReader.readLine();
            Log.v(TAG, "name= " + str);
        } catch (Exception e) {
            Log.v(TAG, "getNodeName: ", e);
        } finally {
            close(in);
            close(bReader);
        }

        return str;
    }

    public StepRankingDTO getStepRanking() throws RemoteException {
        return PushApiClientProxy.fetchBinder().getStepRanking();
    }

}
